import React, { useImperativeHandle, useMemo, useState } from 'react';
import { Modal, Form, Spin, message } from 'antd';
import { useRequest } from '@/hooks';
import {
    queryCandidateProcessDetail,
    updateEntryDate,
    terminateEntry,
    assignHandler
} from '@/pages/EntryManage/services';
import moment from 'moment';
import AbortEntry from './components/AbortEntry';
import ChangeEntryDate from './components/ChangeEntryDate';
import ChangeEntryDateEnd from './components/ChangeEntryDateEnd';
import Designate from './components/Designate';

/**
 * 操作弹窗
 * *
 * onOk回调有2个参数，onOk(res,form)事件中，第一个是请求结果，第二个是form实例
 *
 */

const TITLE_MAP = {
    1: '修改处理人',
    2: '修改入职时间',
    3: '终止入职',
    4: '确认入职时间'
};

const MoreOperateModal = React.forwardRef(
    (
        {
            visible = false,
            onOk,
            onCancel,
            entryPersonnelCode, // state里得code
            operateType,
            form,
            title,
            changeDateCode = '', // 从路由上获取的code
            setModalEntryOperateType,
            ...rest
        },
        ref
    ) => {
        const [submitLoading, setSubmitLoading] = useState(false);
        const [titleName, setTitleName] = React.useState();
        // 请求数据
        const { data = {}, loading } = useRequest(() => queryCandidateProcessDetail(entryPersonnelCode), {
            onSuccess: ({ code, msg, data: data1 }) => {
                if (code !== 10000) {
                    message.error(msg);
                }
                // 如果是从消息跳转到列表页弹窗的时候的判断 如果HR已经处理过候选人要求的更改入职时间后，渲染类型4
                if (data1?.applyEntryDateStatus === 'finished' && changeDateCode) {
                    setModalEntryOperateType(4);
                }
                if (operateType === 2 && data1?.applyEntryDateStatus === 'waitfor' && entryPersonnelCode) {
                    setTitleName('确认入职时间');
                }
            }
        });
        const { data: recordData = {} } = data;

        useImperativeHandle(ref, () => ({
            form
        }));

        // 修改入职时间
        const { run: runUpdateEntryDate } = useRequest(param => updateEntryDate(param), { manual: true });

        // 指派处理人
        const { run: runAssignHandler } = useRequest(param => assignHandler(param), { manual: true });

        // 终止入职
        const { run: runTerminateEntry } = useRequest(param => terminateEntry(param), { manual: true });

        // 渲染内容
        const contentRender = useMemo(() => {
            switch (operateType) {
                case 1:
                    return <Designate form={form} data={recordData} />;
                case 2:
                    return <ChangeEntryDate form={form} data={recordData} />;
                case 3:
                    return <AbortEntry form={form} />;
                case 4:
                    return <ChangeEntryDateEnd form={form} data={recordData} />;
                default:
                    return null;
            }
        }, [form, recordData]);
        return (
            <Modal
                visible={visible}
                title={title || titleName || TITLE_MAP[operateType]}
                width={520}
                confirmLoading={submitLoading}
                onCancel={() => {
                    if (onCancel) {
                        onCancel(form);
                    }
                }}
                onOk={() => {
                    if (operateType === 4) {
                        onCancel(form);
                    } else {
                        form.validateFields(async (err, values) => {
                            const { remark, reason, entryDate, beAssignedEmployeeCode } = values;
                            const payload = {
                                reason,
                                entryPersonnelCode
                            };

                            let res = {};

                            if (!err) {
                                setSubmitLoading(true);
                                if (operateType === 1) {
                                    // 指派处理人
                                    res = await runAssignHandler({
                                        ...payload,
                                        beAssignedEmployeeCode
                                    });
                                } else if (operateType === 2) {
                                    // 修改入职时间
                                    res = await runUpdateEntryDate({
                                        ...payload,
                                        entryDate: moment(entryDate).format('YYYY-MM-DD')
                                    });
                                } else if (operateType === 3) {
                                    // 终止入职
                                    res = await runTerminateEntry({
                                        ...payload,
                                        remark
                                    });
                                }
                                setSubmitLoading(false);

                                if (onOk) {
                                    onOk(res, form);
                                }
                            }
                        });
                    }
                }}
                {...rest}
                destroyOnClose={false}
            >
                <Spin spinning={loading}>
                    <Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                        {contentRender}
                    </Form>
                </Spin>
            </Modal>
        );
    }
);

export default Form.create()(MoreOperateModal);
